package com.kzd.gtgame.main.home

import android.content.Intent
import android.text.Editable
import androidx.lifecycle.LifecycleOwner
import com.kzd.gtgame.R
import com.kzd.gtgame.custom.setOnClickAntiShakeListener
import com.kzd.gtgame.entity.BargainDetails
import com.kzd.gtgame.entity.GamePlayed
import com.kzd.gtgame.entity.GameSmall
import com.kzd.gtgame.jetpack.vm.BargainViewModel
import com.kzd.gtgame.main.KEY_BARGAIN_DETAILS_ENTITY
import com.kzd.gtgame.main.home.adapter.ImageSelectAdapter
import com.kzd.gtgame.main.popup.GameBargainPopup
import com.kzd.gtgame.main.popup.LoadingDialog
import com.module.lemlin.http.Status
import com.module.lemlin.http.msg
import com.module.lemlin.owner.OwnerViewModeActivity
import com.zhihu.matisse.Matisse
import kotlinx.android.synthetic.main.activity_bargain_sell.*
import java.lang.StringBuilder

class BargainSellActivity : OwnerViewModeActivity<BargainViewModel>() {

    private val mBargainDetails: BargainDetails?
        get() = intent?.extras?.getSerializable(KEY_BARGAIN_DETAILS_ENTITY) as? BargainDetails

    private var mGamePlayed: GamePlayed? = null
    private var mGameSmall: GameSmall? = null
    private var mImages: MutableList<String> = mutableListOf()

    private val mGameBargainPopup: GameBargainPopup by lazy {
        GameBargainPopup(context = this, onGamePlayed = { _, gamePlayed ->
            mGameBargainPopup.dismiss()
            this.mGamePlayed = gamePlayed
            tvBargainSellGame.text = gamePlayed.name
            tvBargainSellSmall.text = null
            etBargainSellArea.text = null
        }, onGameSmall = { _, gameSmall ->
            mGameBargainPopup.dismiss()
            this.mGameSmall = gameSmall
            tvBargainSellSmall.text = gameSmall.user_name
            etBargainSellArea.text =
                Editable.Factory.getInstance().newEditable(gameSmall.server_name)
        })
    }

    private val mImageSelectAdapter = ImageSelectAdapter()

    override fun viewModel(): BargainViewModel {
        return createViewModel()
    }

    override val layoutResId: Int
        get() = R.layout.activity_bargain_sell

    override fun stateBar(): StatusBar {
        return StatusBar(color = R.color.white, view = flBargainSellBar)
    }


    override fun initView() {

        rvBargainSellBody.adapter = mImageSelectAdapter.apply {
            setNewInstance(mutableListOf(R.mipmap.photo_add_icon))
        }
        mImageSelectAdapter.setOnItemClickListener { _, _, position ->
            if (position != 0) {
                return@setOnItemClickListener
            }
            viewModel.userMatisse(activity = this, maxSelectable = 7)
        }

        tvBargainSellGame.setOnClickAntiShakeListener {
            viewModel.bargainGame()
        }
        tvBargainSellSmall.setOnClickAntiShakeListener {
            if (mGamePlayed == null) {
                toast("请选择游戏")
            } else mGamePlayed?.let {
                viewModel.bargainGameSmall(it.id, it.appid)
            }
        }
        tvBargainSellSubmit.setOnClickAntiShakeListener {
            when {
                mGamePlayed == null -> toast("请选择游戏")
                mGameSmall == null -> toast("请选择小号")
                etBargainSellArea.text.isNullOrEmpty() -> toast("请填写游戏区服")
                etBargainSellPrice.text.isNullOrEmpty() -> toast("请填写出售价格")
                etBargainSellTitle.text.isNullOrEmpty() -> toast("请填写标题")
                etBargainSellDesc.text.isNullOrEmpty() -> toast("请填写商品描述")
                mImages.isNullOrEmpty() -> toast("请选择图片")
                else -> viewModel.userUpload(images = mImages)
            }
        }
    }

    override fun initData() {

    }

    override fun initViewMode() {
        viewModel.gamePlayedLiveData.observe(this as LifecycleOwner, { response ->
            if (response.status == Status.FAILURE) {
                toast(response.error?.msg)
            }
            if (response.status != Status.SUCCESS)
                return@observe
            val data = response.data?.data
                ?: return@observe
            mGameBargainPopup.fillDataGamePlayed(data)
                .showPopupWindow()
        })
        viewModel.gameSmallLiveData.observe(this as LifecycleOwner, { response ->
            if (response.status == Status.FAILURE) {
                toast(response.error?.msg)
            }
            if (response.status != Status.SUCCESS)
                return@observe
            val data = response.data?.data
                ?: return@observe
            mGameBargainPopup.fillDataGameSmall(data)
                .showPopupWindow()
        })

        viewModel.userUploadLiveData.observe(this as LifecycleOwner, { response ->
            if (response.status == Status.START) {
                LoadingDialog.show(context = this, resId = R.layout.dialog_load_style_1)
            } else if (response.status == Status.FAILURE) {
                toast(response.error?.msg)
            }
            if (response.status != Status.SUCCESS)
                return@observe
            val data = response.data?.data
                ?: return@observe
            if (data.size == 0)
                return@observe
            val images = StringBuilder()
            data.forEach {
                images.append(it).append(",")
            }
            viewModel.bargainSubmit(
                name = etBargainSellTitle.text.toString(),
                game_id = mGamePlayed?.id ?: "",
                introduction = etBargainSellDesc.text.toString(),
                sname = etBargainSellArea.text.toString(),
                small_id = mGameSmall?.small_id ?: "",
                two_passwd = etBargainSellPwd.text.toString(),
                money = etBargainSellPrice.text.toString(),
                system = "1",
                images = images.substring(0, images.length - 1).toString()
            )
        })

        viewModel.bargainSubmitLiveData.observe(this as LifecycleOwner, { response ->
            if (response.status == Status.FAILURE) {
                toast(response.error?.msg)
                LoadingDialog.dismiss()
            }
            if (response.status != Status.SUCCESS)
                return@observe
            LoadingDialog.dismiss()
            toast(response.data?.message)
            finish()
        })
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 100 && resultCode == RESULT_OK) {
            val pathList: MutableList<String> = Matisse.obtainPathResult(data).toMutableList()
            if (pathList.size == 0)
                return
            val images: MutableList<Any> = mutableListOf()
            images.add(R.mipmap.photo_add_icon)
            pathList.forEach {
                images.add(it)
            }
            mImageSelectAdapter.setNewInstance(images)
            mImages.clear()
            mImages.addAll(pathList)
        }
    }


}